import { ref, onMounted, onUnmounted } from 'vue';

export const useFullScreen = () => {
  const isFull = ref(false);

  function fullScreen() {
    isFull.value ? exit(document) : enter(document.documentElement);
  }

  function updateFullscreenStatus() {
    isFull.value = !!(
      document.fullscreenElement ||
      document.mozFullscreenElement ||
      document.webkitFullscreenElement ||
      document.msFullscreenElement ||
      null
    );
  }

  function onNativeFullscreenChange(e: KeyboardEvent) {
    if (e.key === 'F11') {
      e.preventDefault();
      fullScreen();
    }
  }

  function enter(ele: any) {
    if (ele.requestFullscreen) {
      ele.requestFullscreen();
    } else if (ele.mozRequestFullscreen) {
      ele.mozRequestFullscreen();
    } else if (ele.webkitRequestFullscreen) {
      ele.webkitRequestFullscreen();
    } else if (ele.msRequestFullscreen) {
      ele.msRequestFullscreen();
    }
    isFull.value = true;
  }

  function exit(ele: any) {
    if (ele.exitFullscreen) {
      ele.exitFullscreen();
    } else if (ele.mozExitFullscreen) {
      ele.mozExitFullscreen();
    } else if (ele.webkitExitFullscreen) {
      ele.webkitExitFullscreen();
    } else if (ele.msExitFullscreen) {
      ele.msExitFullscreen();
    }
    isFull.value = false;
  }

  onMounted(() => {
    document.addEventListener('keydown', onNativeFullscreenChange);
    document.addEventListener('fullscreenchange', updateFullscreenStatus);
  });
  onUnmounted(() => {
    document.removeEventListener('keydown', onNativeFullscreenChange);
    document.removeEventListener('fullscreenchange', updateFullscreenStatus);
  });

  return {
    isFull,
    fullScreen
  };
};
